<?php

/**
 * Crc CMS
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage User
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @copyright  Copyright (c) 2012
 * @version    $Id: indexController.php 67 2013-02-22 17:15:36Z mcalin45@gmail.com $
 */



/**
 *  User controller
 *
 * @category   Crc
 * @package    Crc_Modules
 * @subpackage User
 * @author     Moldovan Calin <mcalin45@gmail.com>
 * @author     Vlad Razvan <razvanvlad1982@yahoo.com>
 * @copyright  Copyright (c) 2012
 */


class User_IndexController extends Zend_Controller_Action
{
    /**
     * @var Bisna\Application\Container\DoctrineContainer
     */
    protected $doctrine;

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $entityManager;

    public function init()
    {
        $this->doctrine = Zend_Registry::get('doctrine');
        $this->entityManager = $this->doctrine->getEntityManager();
    }

    /**
     * Log a user
     *
     * @return void
     */
    public function loginAction()
    {
        $formOptions = array('submitName' => 'Login');
        $form = new Modules_User_Forms_User();
        $form->addSubForm($form, 'login', $formOptions);

        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost('login');
            if ($form->isValid($formData)) {
                $authAdapter = new Crc_Auth_Adapter_Doctrine2();
                $authAdapter->setEm($this->entityManager)
                            ->setEntityName('Crc\Entity\User')
                            ->setIdentityColumn('email')
                            ->setCredentialColumn('pass')
                            ->addCondition('status', 1)
                            ->addProcess('post', 'processPassForAuth');

                $authAdapter->setIdentity($formData['email'])
                            ->setCredential($formData['pass']);

                $result = $authAdapter->authenticate();

                switch ($result->getCode()) {
                    case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                        $msg = 'User does not exist.';
                        break;

                    case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                        $msg = 'Invalid data.';
                        break;

                    case Zend_Auth_Result::SUCCESS:
                        if ($userInfo = $result->getIdentity()) {
                            Zend_Auth::getInstance()->getStorage()->write($userInfo);
                            $this->_redirect('/user/admin/');
                        } else {
                            $msg = 'There is a problem with the server. Please try again later';
                        }
                        break;

                    default:
                        $msg = 'There is a problem with the server. Please try again later.';
                        break;
                }
            } else {
                $msg = 'The user and password do not match.';
            }
            $this->view->msg = $msg;
        }
        $this->view->form = $form;
    }


    /**
     * Logout user
     *
     * @return void
     */
    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }


    /**
     * Recover pass for a user
     *
     * @return void
     */
    public function recoverPassAction()
    {
        $formOptions = array('submitName' => 'Recover pass');
        $form = new Modules_User_Forms_User();
        $form->addSubForm('recoverPass', $formOptions);

        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('recoverPass');
                $users = new Application_Model_Collection_User();
                $user = $users->getUserByEmail($formData['email']);
                $user->generateToken()->save();
                 // create view object
                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/modules/user/views/scripts/email/');

                // assign values
                $html->assign('name', $user->getName());
                $link = APPLICATION_URL . '/user/index/change-pass/token/' . $user->getToken();
                $html->assign('linkRecoverPass', $link);

                // render view
                $bodyText = $html->render('recover-pass.phtml');
                $mail = new Zend_Mail('utf-8');
                $mail->setBodyHtml($bodyText);
                $mail->setFrom('no-reply@zf-pescuit.dev', 'Pescuit Info');
                $mail->addTo($user->getEmail(), $user->getName());
                $mail->setSubject('Password recovery');
                $mail->send();
                $this->view->message = 'An e-mail containing the recover password link has been sent';
            }
        }
        $this->view->form = $form;
    }



    /**
     * Change password for a user
     *
     * @return void
     */
    public function changePassAction()
    {
        $users = new Application_Model_Collection_User();
        $user = $users->getUserByToken($this->getRequest()->getParam('token'));
        if (!$user)
        {
            $this->view->message = 'The token is not valid';
        }

        $formOptions = array('submitName' => 'Change pass');
        $form = new Modules_User_Forms_User();
        $form->addSubForm('changePass', $formOptions);
        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('changePass');
                $user->setToken('');
                $user->generatePassword($formData['pass']);
                $user->save();
                $this->view->message = 'Congratulations. Now you can login using the new password';
            }
        }
        $this->view->form = $form;
    }

    /**
     * Register a new user action
     *
     * @return void
     */
    public function registerAction()
    {
        if (Zend_Auth::getInstance()->hasIdentity())
        {
            $this->_helper->redirector->gotoSimpleAndExit('logout','index','user');
        }
        $formOptions = array('submitName' => 'Register');
        $form = new Modules_User_Forms_User();
        $form->addSubForm('register', $formOptions);
        if ($this->getRequest()->isPost())
        {
            if ($form->isValid($this->getRequest()->getPost()))
            {
                $formData = $this->getRequest()->getPost('register');
                unset($formData['cpass']);
                $users = new Application_Model_Collection_User();
                $user = $users->createRow();
                $user->setFromArray($formData);
                $user->generatePassword($formData['pass']);
                $user->setStatus(0);
                $user->setIdAclRole(1);
                $user->generateToken()->save();

                $html = new Zend_View();
                $html->setScriptPath(APPLICATION_PATH . '/modules/user/views/scripts/email/');

                $link = APPLICATION_URL . '/user/index/confirm-registration/token/' . $user->getToken();
                $html->assign('name', $user->getName());
                $html->assign('link', $link);
                $bodyText = $html->render('register.phtml');
                $mail = new Zend_Mail();
                $mail->setBodyHtml($bodyText);
                $mail->addTo($user->getEmail());
                $mail->setSubject('Registration confirmation');
                $mail->send();
                $this->_redirect('/user/index/after-register/userId/'.$user->getId());
            }
        }
        $this->view->form = $form;
    }



    /**
     * Display this page after user registers
     *
     * @return void
     */
    public function afterRegisterAction()
    {
        $users = new Application_Model_Collection_User();
        $user = $users->find($this->getRequest()->getParam('userId'))->current();
        $this->view->user = $user;
    }



    /**
     * Confirm registration page
     *
     * @return void
     */
    public function confirmRegistrationAction()
    {
        $token = $this->getRequest()->getParam('token');
        $users = new Application_Model_Collection_User();
        $user = $users->getUserByToken($token);
        if ($user)
        {
            $user->setToken('')->setStatus(1)->save();
            $this->view->user = $user;
            $this->view->confirm = true;
        }
        else
        {
            $this->view->confirm = false;
        }
    }
}